package siwi.map.android;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.LayoutParams;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.ActionBar.TabListener;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.wmw.DataPool.CommonData;
import com.wmw.Utility.Common;
import com.wmw.Utility.DBConstant;

public class Home extends SherlockFragmentActivity implements
		OnClickListener, OnPageChangeListener {
	// 1.二维码扫描结账.
	public static final int _TAG_HOME = 0;
	public static final int _TAG_PERSONAL_CENTER = 1;
	public static final int _TAG_ORDER = 2;
	public static final int _TAG_HISTORY = 3;
	public static final int _TAG_SETTING = 4;
	public static final int _ITEMS_NUM = 5;

	static final int COLOR1 = Color.parseColor("#787878");
	static final int COLOR2 = Color.parseColor("#00ff00");

	OnFragmentListener[] _fragmentsListener;
	MyAdapter adapter;
	
	DBConstant.DatabaseHelper _openDBHelper;
	
	ViewPager mPager;
	int mCurTabId, _curTabIdx = -1;

	private TextView _title;
	private ImageButton _status;
	int []_statusIDs = new int[3];

	ImageView[] _imageViews = new ImageView[_ITEMS_NUM];
	TextView[] _textViews = new TextView[_ITEMS_NUM];
	int[] _layoutIDs = new int[_ITEMS_NUM];
	int[] _drawableBtnDownIDs = new int[_ITEMS_NUM];
	int[] _drawableBtnNormalIDs = new int[_ITEMS_NUM];

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// setTheme(R.style.Theme_Sherlock_Light);
		
		initActionBar();
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home_table);

		initViews();
		initData();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		// adapter.get
		// String tabTag = getTabHost().getCurrentTabTag();
		// Activity activity =
		// getSupportFragmentManager().findFragmentByTag(tabTag);
		// Log.d(Common.GetLineInfo(), "Current using activity:" + "tabTag -" +
		// tabTag + ", activity -" + activity);
		//
		// Orders o = (Orders)activity;
		// o.onNewIntent(intent);
	}

	@Override
	public void onClick(View v) {
		if (mCurTabId == v.getId()) {
			return;
		}

		clearTabViews();

		int checkedId = v.getId();
		for (int i = 0; i < _ITEMS_NUM; ++i)
			if (checkedId == this._layoutIDs[i]) {
				mPager.setCurrentItem(i);
				setTabViewClicked(i);
				break;
			}

		mCurTabId = checkedId;
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		return new AlertDialog.Builder(Home.this)
				.setTitle("")
				.setItems(R.array.RestaurantStatus,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								String[] items = getResources().getStringArray(
										R.array.RestaurantStatus);
								Log.d(Common.GetLineInfo(), "You selected: "
										+ which + " , " + items[which]);
								// TODO
								Common.toastInfo(Home.this, "修改运营状态");
								
								_status.setImageResource(_statusIDs[which]);
							}
						}).create();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		_openDBHelper.close();
	}

	private void initActionBar(){
		ActionBar actionBar = getSupportActionBar();
		ActionBar.LayoutParams params = new ActionBar.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,
				Gravity.LEFT);
		View view = LayoutInflater.from(this).inflate(
				R.layout.home_action_bar, null);
		actionBar.setCustomView(view, params);
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);
	}
	
	private void initViews(){
		adapter = new MyAdapter(getSupportFragmentManager());
		mPager = (ViewPager) findViewById(R.id.pager);
		mPager.setAdapter(adapter);
		mPager.setOnPageChangeListener(this);

		prepareView();
		_title = (TextView) findViewById(R.id.MTAB_Title);
		_status = (ImageButton) findViewById(R.id.MTAB_Status);

		processDataFromLogin();
		findViewById(R.id.MTAB_Avatar).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						Toast.makeText(Home.this, "Avatar clicked", Toast.LENGTH_SHORT).show();
						Intent intent = new Intent();
						intent.setClass(Home.this, PersonalCenter.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
						startActivity(intent);
					}

				});

		findViewById(R.id.MTAB_StatusLayout).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						showDialog(0);
					}

				});
	}
	
	private void initData(){
		ExApplication app = (ExApplication)getApplication();
		_openDBHelper = app._openDBHelper;
	}
	
	private void processDataFromLogin(){
		// TODO
		// 时间为空串时,直接在这里增加一个给他
		Common.toastInfo(Home.this, "登录后传过来的参数");
		Intent intent = getIntent();
		Log.d(Common.GetLineInfo(), "" + getIntent().getIntExtra("a", 0));
		String realName = "店主姓名";
		String username = "jxtgddlt";
		String storeNmae = "食人之家";
		String []address ={ "湖南省衡阳市珠晖区湖南省衡阳市珠晖区湖南省衡阳市珠晖区湖南省衡阳市珠晖区", "通达驾校对面通达驾校对面通达驾校对面" };
		String []phoneNumber = {"15677430002"/*, "15677430002", "15677430002"*/};
		String []businessHours = {"10:30 ~ 13:30"/*, "16:30 ~ 18:30", "7:00 ~ 9:00"*/};
		String briefIntroduction = "机器人餐厅, 未来心生活";
		float minSendingPrice = 1.5f;
		float sendingPrice = 0.5f;
		
		ExApplication app = (ExApplication)getApplication();
		CommonData data = app._Data;
		data.set_realName(realName);
		data.set_username(username);
		data.set_storeName(storeNmae);
		data.set_Address(address);
		data.set_phoneNumber(phoneNumber);
		data.set_businessHours(businessHours);
		data.set_briefIntroduction(briefIntroduction);
		data.set_minimumSendingPrice(minSendingPrice);
		data.set_sendingPrice(sendingPrice);
		_title.setText(storeNmae);
	}
	private void prepareView() {
		TypedArray taStatusResource = getResources().obtainTypedArray(
				R.array.RestaurantStatusResource);
		for (int i = 0; i < 3; ++i) {
			_statusIDs[i] = taStatusResource.getResourceId(i, 0);
		}
		taStatusResource.recycle();
		
		TypedArray taIV = getResources().obtainTypedArray(
				R.array.MainTableImageViews);
		int[] resIDs = new int[_ITEMS_NUM];
		for (int i = 0; i < _ITEMS_NUM; ++i) {
			resIDs[i] = taIV.getResourceId(i, 0);
			Log.d(Common.GetLineInfo(), "Creating ImageView -" + i);
			_imageViews[i] = (ImageView) findViewById(resIDs[i]);
		}
		taIV.recycle();
		
		TypedArray taTV = getResources().obtainTypedArray(
				R.array.MainTableTextViews);
		int[] resTVIDs = new int[_ITEMS_NUM];
		for (int i = 0; i < _ITEMS_NUM; ++i) {
			resTVIDs[i] = taTV.getResourceId(i, 0);
			if (resTVIDs[i] != 0) {
				Log.d(Common.GetLineInfo(), "Creating TextView -" + i);
				_textViews[i] = (TextView) findViewById(resTVIDs[i]);
			}
		}
		taTV.recycle();

		TypedArray taLayoutIDs = getResources().obtainTypedArray(
				R.array.MainTableChannels);
		if (_layoutIDs.length != taLayoutIDs.length())
			Log.e(Common.GetLineInfo(), "Layout length doesn't equal");
		for (int i = 0; i < _ITEMS_NUM; ++i) {
			_layoutIDs[i] = taLayoutIDs.getResourceId(i, 0);
			findViewById(_layoutIDs[i]).setOnClickListener(this);
		}
		taLayoutIDs.recycle();

		TypedArray taDrawableBtnDownIDs = getResources().obtainTypedArray(
				R.array.MainTableDrawableOnBtnDown);
		if (_drawableBtnDownIDs.length != taDrawableBtnDownIDs.length())
			Log.e(Common.GetLineInfo(),
					"Drawable Button Downs' length doesn't equal");
		for (int i = 0; i < _ITEMS_NUM; ++i)
			_drawableBtnDownIDs[i] = taDrawableBtnDownIDs.getResourceId(i, 0);
		taDrawableBtnDownIDs.recycle();

		TypedArray taDrawableBtnNormalIDs = getResources().obtainTypedArray(
				R.array.MainTableDrawableOnBtnNormal);
		if (_drawableBtnNormalIDs.length != taDrawableBtnNormalIDs.length())
			Log.e(Common.GetLineInfo(),
					"Drawable Button Normals' length doesn't equal");
		for (int i = 0; i < _ITEMS_NUM; ++i)
			_drawableBtnNormalIDs[i] = taDrawableBtnNormalIDs.getResourceId(i,
					0);
		taDrawableBtnNormalIDs.recycle();

	}

	private void clearTabViews() {
		for (int i = 0; i < _ITEMS_NUM; ++i) {
			_imageViews[i].setImageResource(_drawableBtnNormalIDs[i]);
			if (_textViews[i] != null)
				_textViews[i].setTextColor(COLOR1);
		}
	}

	private void setTabViewClicked(int idx) {
		if (idx >= 0 && idx < _ITEMS_NUM) {
			_imageViews[idx].setImageResource(_drawableBtnDownIDs[idx]);
			if (_textViews[idx] != null)
				_textViews[idx].setTextColor(COLOR2);
		}
	}

	// The container Activity must implement this interface so the frag can
	// deliver messages
	public interface OnFragmentListener {
		/** Called by HeadlinesFragment when a list item is selected */
		public void onFragmentResume(Intent intent);
	}

	public class MyAdapter extends FragmentStatePagerAdapter {
		public MyAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public int getCount() {
			return _ITEMS_NUM;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return ((ExApplication)getApplication())._Data.get_storeName();
		}

		@Override
		public Fragment getItem(int position) {
			Fragment fragment = null;
			switch (position) {
			case _TAG_HOME:
				fragment = MyHome.newInstance(_openDBHelper);
				break;

			case _TAG_PERSONAL_CENTER:
				fragment = StoreCenter.newInstance(_openDBHelper);
				break;

			case _TAG_ORDER:
				fragment = Orders.newInstance(_openDBHelper);
				break;

			case _TAG_HISTORY:
				fragment = History.newInstance(_openDBHelper);
				break;

			case _TAG_SETTING:
				fragment = Setting.newInstance(position);
				break;

			default:
				Log.d(Common.GetLineInfo(), "Unexpected error");
				break;
			}
			return fragment;
		}
	}


	@Override
	public void onPageScrollStateChanged(int state) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageSelected(int position) {
		// TODO Auto-generated method stub
		if (_curTabIdx != position) {
			clearTabViews();
			_curTabIdx = position;
			setTabViewClicked(position);

			Log.d(Common.GetLineInfo(), "" + adapter.getPageTitle(position));
			_title.setText(adapter.getPageTitle(position));
			supportInvalidateOptionsMenu();
		}
	}


}
